<template>
<q-dialog persistent fixed v-model="isMapDialog" :maximized="$q.platform.is.mobile" position="standard" transition-show="slide-up" transition-hide="slide-down">
    <q-layout view="hHh Lpr fFf" container class="bg-dark hide-scrollbar">
        <q-header class="bg-grey-10 shadow-7">

            <q-toolbar>
                <q-toolbar-title>位置选择</q-toolbar-title>
                <q-space />

                <q-btn dense flat icon="close" @click="trigerUpdate('close')">
                </q-btn>
            </q-toolbar>

        </q-header>
        <q-footer class="bg-grey-10 text-white  shadow-up-7">
          <div class="row items-center justify-between q-py-md q-px-md no-wrap">
            <!-- <q-icon size="25px" name="mdi-map-marker-outline"></q-icon> -->
            <div class="column ">
              <span class="text-h6 q-pr-md">{{ address.name }}</span>
              <span class="text-caption">{{address.region}}</span>
            </div>
            <div class="column items-center">
              <q-btn round  outline icon="mdi-navigation-outline"  @click="handleNav" color="primary" ></q-btn>
              <span class="text-caption q-mt-sm">导航</span>
            </div>


          </div>
          <q-separator v-if="isEdit" color="grey-8"></q-separator>


            <q-toolbar v-if="isEdit" class="q-pa-sm" dense inset>

                <q-space></q-space>

                <q-btn  dense  outline class="q-px-md" @click="submitPosition"> 确认</q-btn>
            </q-toolbar>
        </q-footer>
        <q-page-container>
            <q-page class="bg-dark column hide-scrollbar">

                <q-select v-if="isEdit" class="col-auto" dense filled dark v-model="searchName" use-input input-debounce="200" label="拍摄地" :options="addressOptions" @input-value="handleSearch" option-label="name" @input="handleConfirmName">
                    <template v-slot:no-option>
                        <q-item>
                            <q-item-section class="text-grey">
                                没有地点
                            </q-item-section>
                        </q-item>
                    </template>
                </q-select>
                <!-- <q-input class="col-auto" v-model="searchName" dark filled @input="handleSearch" placeholder="请输入地点"></q-input> -->
                <div class="full-width col-grow" style="height:100px" id="container"> </div>
                <q-dialog persistent fixed v-model="isNavDialog" maximized position="standard" transition-show="slide-up" transition-hide="slide-down">
                  <q-layout view="hHh Lpr fFf" container class="bg-dark hide-scrollbar">
                      <q-header class="bg-grey-10 shadow-7">

                          <q-toolbar>
                              <q-toolbar-title>导航</q-toolbar-title>
                              <q-space />

                              <q-btn dense flat icon="close" @click="isNavDialog=false">
                              </q-btn>
                          </q-toolbar>

                      </q-header>

                      <q-page-container>
                          <q-page class="bg-dark column hide-scrollbar">
                             <iframe class="col-grow" :src="navPath" frameborder="0"></iframe>

                          </q-page>
                      </q-page-container>

                  </q-layout>

              </q-dialog>

            </q-page>
        </q-page-container>

    </q-layout>


</q-dialog>
</template>

<script>
import AMapLoader from '@amap/amap-jsapi-loader';

window._AMapSecurityConfig = {
    securityJsCode: '834380a43d1b2ef09fe547423f3bff34',
}
export default {
    name: 'createTask',
    components: {

    },
    props: {
        isMapDialog: {
            default: false
        },
        user: {
            type: Object
        },
        place: {
            type: Object
        },
        isEdit:{
          default:true,
        }
    },
    data() {
        return {
            searchName: '',
            addressOptions: [],
            address: {
              name: '',
              region:'' ,
              position:''
            },
            isNavDialog:false,
            navPath:''

        }
    },
    watch: {

        isMapDialog: function (val) {
            console.log(val, 'createTask');

            if (val) {
              if(this.place.name){
                this.searchName = this.place.name
              }

                setTimeout(() => {
                    this.initAMap()
                    // var iframe = document.getElementById('test').contentWindow;
                    // document.getElementById('test').onload = function () {
                    //     iframe.postMessage('hello', 'https://m.amap.com/picker/');
                    // };
                    // window.addEventListener("message", function (e) {
                    //     alert('您选择了:' + e.data.name + ',' + e.data.location)
                    // }, false);
                }, 200)

            }
        },
        place: function (val) {

        }
    },
    mounted() {
        //  this.initAMap()

    },
    beforeDestroy() {
      if(this.map){
        this.map.destroy()
      }
      this.$q.loading.hide()

    },
    methods: {
      handleNav(){
        let address = this.address;
        let from = "114.355444, 30.526555"
        let to = address.position[0]+',' +address.position[1];

          this.navPath =  `https://uri.amap.com/navigation?from=${from},公司&to=${to},拍摄地&mode=car&policy=1&src=mypage&coordinate=gaode&callnative=1`;
          this.isNavDialog=true;
      },
        canclePosition() {

        },
        submitPosition() {
            this.$emit('update:place',this.address);
            this.trigerUpdate()
        },
        trigerUpdate() {
            this.curAddressName="";
            this.searchName=""
            this.$emit('update')
        },
        filterFn(val, update) {
            if (val === '') {
                update(() => {
                    this.addressOptions = []

                    // with Quasar v1.7.4+
                    // here you have access to "ref" which
                    // is the Vue reference of the QSelect
                })
                return
            }

            update(() => {
                const needle = val.toLowerCase()
                console.log(needle);
                this.handleSearch(needle)
                // this.options = stringOptions.filter(v => v.toLowerCase().indexOf(needle) > -1)
            })
        },
        handleSearch(val) {

            // var points = [{
            //                   keyword: '中部创意大厦',
            //                   city: '武汉'
            //               },
            //               {
            //                   keyword: '华中师范大学',
            //                   city: '武汉'
            //               }
            //           ]

            // 搜索完成后，将自动绘制路线到地图上
            //this.driving.search(points)
            this.autoComplete.search(val, (status, result) => {
                // 搜索成功时，result即是对应的匹配数据

                if (result.info == "OK") {
                    this.addressOptions = result.tips;
                }
            })

            // this.placeSearch.search(this.searchName);
        },
        handleConfirmName(v) {
            console.log('confirm', v);
            // var position = []; // 标准写法
            // // 简写 var position = [116, 39];
            if (v != null) {
                console.log(v.location.lat, v.location.lng);
                var position = [v.location.lng, v.location.lat]
                this.map.setCenter(position);
            }

            // this.searchName=v.name
        },

        initAMap() {
            this.$q.loading.show({
                customClass: 'mypage-loading',
                message: '<span class="text-white text-weight-bold">加载中...</span>'
            })

            AMapLoader.load({
                key: '4a5a3ef441d52a9341353c1720065bcb', //设置您的key
                version: "2.0",
                plugins: ['AMap.ToolBar', 'AMap.Driving', "AMap.AutoComplete", "AMap.PlaceSearch", 'AMap.Geolocation', "AMap.Geocoder"],
                AMapUI: {
                    version: "1.1",
                    plugins: [],

                },
                Loca: {
                    version: "2.0"
                },
            }).then((AMap) => {
                console.log(AMap);
                this.map = new AMap.Map("container", {
                    mapStyle: 'amap://styles/fresh',
                    viewMode: "3D",
                    pitch: 45,
                    zoom: 15,
                    touchZoomCenter: 1,
                    features: ['bg', 'point', 'road', 'building'],
                    showBuildingBlock: true,
                    center: [114.355444, 30.526555],
                    marks: [{}]

                });
                this.map.on('complete', () => {
                    // 地图图块加载完成后触发
                    this.$q.loading.hide();
                    this.handleMapMoveEnd()

                });

                var vm = this;
                AMap.plugin('AMap.Geolocation', function () {
                    vm.map.addControl(new AMap.Geolocation());

                })
                AMap.plugin("AMap.Geocoder", function () {
                    var autoOptions = {
                        //city 限定城市，默认全国
                        city: '全国'
                    };
                    vm.geoLocation = new AMap.Geocoder(autoOptions);

                })
                AMap.plugin('AMap.AutoComplete', function () {
                    var autoOptions = {
                        //city 限定城市，默认全国
                        city: '全国'
                    };
                    // 实例化AutoComplete
                    vm.autoComplete = new AMap.AutoComplete(autoOptions);
                    // 根据关键字进行搜索

                })
                this.placeSearch = new AMap.PlaceSearch({
                    map: this.map,
                    panel: "panel", // 结果列表将在此容器中进行展示。
                    // city: "010", // 兴趣点城市
                    autoFitView: true, // 是否自动调整地图视野使绘制的 Marker点都处于视口的可见范围
                    extensions: 'base' //返回基本地址信息
                });

                AMap.plugin('AMap.Driving', function () {
                    vm.driving = new AMap.Driving({
                        // 驾车路线规划策略，AMap.DrivingPolicy.LEAST_TIME是最快捷模式
                        policy: AMap.DrivingPolicy.LEAST_TIME,
                        // map 指定将路线规划方案绘制到对应的AMap.Map对象上
                        map: vm.map,
                        // panel 指定将结构化的路线详情数据显示的对应的DOM上，传入值需是DOM的ID
                        panel: 'panel'
                    })

                })
                if (this.searchName) {
                  if(this.place.position){
                    this.map.setCenter(this.place.position)
                  }else{
                    this.placeSearch.search(this.place.name)
                  }

                }

                this.marker = new AMap.Marker({

                    position: new AMap.LngLat(114.355444, 30.526555), // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]
                    title: '一方映画'
                });
                console.log(this.marker);

                this.map.add(this.marker);
                this.map.on('click', function (e) {
                    console.log("经度", e.lnglat.getLng())
                    console.log("纬度", e.lnglat.getLat())
                });
                this.map.on('mapmove',
                    this.handleMapMove
                );
                this.map.on('resize',
                    this.handleMapMove
                );
                this.map.on('moveend',
                    this.handleMapMoveEnd
                );

            }).catch(e => {
                console.log(e);
            })
        },
        handleMapMove(e) {

            var center = this.map.getCenter();

            this.marker.setPosition([center.lng, center.lat])
            // var centerMark = new AMap.Marker({
            //     position: position, // 经纬度对象，也可以是经纬度构成的一维数组[116.39, 39.9]

            // });
            // this.map.add(centerMark)
        },
        handleMapMoveEnd() {

            this.geoLocation.getAddress(this.marker.getPosition(), (status, res) => {
                console.log(res,this.marker.getPosition());
                let province = res.regeocode.addressComponent.province;
                let city = res.regeocode.addressComponent.city;
                let district = res.regeocode.addressComponent.district;
                let street = res.regeocode.addressComponent.street;
                let township = res.regeocode.addressComponent.township;
                let streetNum = res.regeocode.addressComponent.streetNumber;



                this.address.name = res.regeocode.formattedAddress.replace(province,'').replace(city,'').replace(district,'').replace(street,'').replace(township,'').replace(streetNum,'');
                this.address.region = res.regeocode.formattedAddress.replace(this.address.name,'')
                let p = this.marker.getPosition()
                this.address.position= [p.lng,p.lat]
                this.addressOptions = res.regeocode.addressComponent.businessAreas

            })
        },
        select(e) {
            this.placeSearch.setCity(e.poi.adcode);
            this.placeSearch.search(e.poi.name); //关键字查询查询
        }

    }
}
</script>

<style scoped>
/* 隐藏高德logo  */
.amap-logo {
    display: none !important;
}

/* 隐藏高德版权  */
.amap-copyright {
    display: none !important;
}
</style>
